﻿using MyCompany.MyProject.Model.Models;
using MyCompany.MyProject.Repository.Base;
using MyCompany.MyProject.Repository.UnitOfWork;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompany.MyProject.Repository;

public class RoleModulePermissionRepository : BaseRepository<RoleModulePermission>, IRoleModulePermissionRepository
{
    public RoleModulePermissionRepository(IUnitOfWorkManage unitOfWork) : base(unitOfWork)
    {
    }

    /// <summary>
    /// 角色权限 Map
    /// RoleModulePermission, Modules, Role 三表联合
    /// 第四个 RoleModulePermission 是返回值
    /// </summary>
    /// <returns></returns>
    public async Task<List<RoleModulePermission>> RoleModuleMaps()
    {
        var res = await QueryMuch<RoleModulePermission, Modules, Role, RoleModulePermission>((rmp, m, r) => new object[]
        {
            JoinType.Left,rmp.ModuleId==m.Id,
            JoinType.Left,rmp.RoleId==r.Id
        }, (rmp, m, r) => new RoleModulePermission()
        {
            Role = r,
            Modules = m,
            IsDeleted = rmp.IsDeleted,
        }, (rmp, m, r) => rmp.IsDeleted == false && m.IsDeleted == false && r.IsDeleted == false&&m.Enabled==true);
        return res;
    }

    public async Task UpdateModuleId(long permissionId, long moduleId)
    {
        await Db.Updateable<RoleModulePermission>(i=>i.ModuleId==moduleId)
              //.SetColumns(it => new RoleModulePermission() { ModuleId = moduleId })
              .Where(it => it.PermissionId == permissionId)
              .ExecuteCommandAsync();
    }
}
